import React, { Component } from 'react';
import { AutoComplete, Form, Modal, Select, Input, Button, Card } from 'antd';
import { FormattedMessage, formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';

const { Option } = Select;
const AutoCompleteOption = AutoComplete.Option;
let modalType = null;
const formItemLayout = {
  labelCol: {
    xs: { span: 5 },
    sm: { span: 5  },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 12 },
  },
};


class EditModal  extends Component  {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      modalType: null,
      name:'',
      id: '',
      fieldType: 'string',
      methods: 'add',
      childrenObj:{
        name:'',
        id: '',
        fieldType: 'string',
      },
      childrenArr: [],
      display:'none'
    };
    this.handleSelectChange = this.handleSelectChange.bind(this)
  }



  showModal = (type,val,method) => {
    console.log(type, '-----------type',val,method);
    if(val){
      this.setState({
        visible: true,
        modalType: type,
        name: val.name,
        id: val.id,
        fieldType: val.fieldType
      });
      console.log(val.children,'------------------children');
      if(val.children.length>0){
          this.setState({
            childrenArr:val.children
          })
      }
    }else{
      this.setState({
        visible: true,
        modalType: type,
        name:'',
        id: '',
        fieldType: 'string',
      });
    }
    if(method){
      this.setState({
        methods: method
      })
    }else{
      this.setState({
        methods: 'add'
      })
    }
    modalType = type;
  };



  handleCancel = (e) => {
    this.setState({
      visible: false,
    });
    this.props.form.resetFields()
  };

  saveField =(e)=>{
    e.preventDefault();
    const { addRequestFieldFun } = this.props;
    const type = this.state.modalType;
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const fieldObj = values;
        fieldObj['type']= modalType;
        if(values.fieldType ==='array'){
          const childrenObj ={
            name:values.names,
            id:values.ids,
            fieldType:values.fieldTypes,
            children:[]
          };
          const childrenArr = [];
          childrenArr.push(childrenObj);
          fieldObj['children'] = childrenArr;
          delete values['names'];
          delete values['ids'];
          delete values['fieldTypes'];
        }else{
          fieldObj['children'] = [];
        }
        addRequestFieldFun (values, modalType,this.state.methods);
        this.handleCancel();
        this.props.form.resetFields()
      }
    });
  };

  checkField(rule, value, callback){
    if(/^[0-9a-zA-Z.]{0,}$/g.test(value))
    {
     callback()
    }else{
      callback('字段名只能输入英文数字小数点')
    }
  };

  addChildren(){
    console.log('继续添加');
    const  that = this;
    const arr = that.state.childrenArr;
    arr.push({
      name:'',
      id:'',
      fieldType:'string',
      btn:true
    });
    that.setState({
      childrenArr:arr,
    },()=>{
      console.log(this.state)
    })

  }

  handleSelectChange(value){
    const  that = this;
    if(value == 'array'){
      that.setState({
        display:'block'
      });
    }
    that.setState({
      fieldType: value,
    });
    that.addChildren();
  }



  render() {
    const { getFieldDecorator } = this.props.form;
    // @ts-ignore
    return (
       <div>
         <Modal
           title={<FormattedMessage id="app.customApi.addOrEditField"  />}
           visible={this.state.visible}
           onOk={this.saveField}
           onCancel={this.handleCancel}
           okText={<FormattedMessage id="app.customApi.apiSave"  />}
           cancelText={<FormattedMessage id="app.customApi.apiCancel"  />}
         >
           <Form {...formItemLayout} onSubmit={this.saveField}>
             <Form.Item
               label={<FormattedMessage id="app.customApi.Field-service-name" />}
               hasFeedback
             >
               {getFieldDecorator('name', {
                 rules: [{
                   required: true, message: '字段业务名不可为空',
                 },{
                   validator: '',
                 }],
                 initialValue: this.state.name
               })(
                 <Input placeholder="请输入字段业务名"   />
               )}
             </Form.Item>
             <Form.Item
               label={<FormattedMessage id="app.customApi.Field-name" />}
               hasFeedback
             >
               {getFieldDecorator('id', {
                 rules: [{
                   required: true, message: '请输入字段名',
                 },{
                   validator: this.checkField,
                 }],
                 initialValue: this.state.id
               })(
                 <Input placeholder="请输入字段名"  />
               )}
             </Form.Item>
             <Form.Item
               label={<FormattedMessage id="app.customApi.Field-type" />}
               hasFeedback

             >
               {getFieldDecorator('fieldType', {
                 rules: [{
                   required: true, message: '请选择字段类型',
                 },{
                   validator: '',
                 }],
                 initialValue:  this.state.fieldType
               })(
                 <Select onChange={this.handleSelectChange}>
                   <Option value="string">字符串(string)</Option>
                   { modalType ==='responseField'? <Option value="array">数组(array)</Option>:''}
                   <Option value="boolean">布尔值(boolean)</Option>
                   <Option value="short">短整型(short)</Option>
                   <Option value="int">整型(int)</Option>
                   <Option value="long">长整型(long)</Option>
                   <Option value="double">双精度型(double)</Option>
                   <Option value="float">浮点型(float)</Option>
                 </Select>
               )}
             </Form.Item>
             {this.state.fieldType === 'array'
               ?
                 this.state.childrenArr.map((obj,index) => {
                  return (
                    <div key={obj.id}>
                      <Form.Item
                        label={<FormattedMessage id="app.customApi.Field-service-name"/>}
                        hasFeedback
                      >
                        {getFieldDecorator('names', {
                          rules: [{
                            required: true, message: '字段业务名不可为空',
                          }, {
                            validator: '',
                          }],
                          initialValue: obj.id
                        })(
                          <Input placeholder="请输入字段业务名"/>
                        )}
                      </Form.Item>
                      <Form.Item
                        label={<FormattedMessage id="app.customApi.Field-name"/>}
                        hasFeedback
                      >
                        {getFieldDecorator('ids', {
                          rules: [{
                            required: true, message: '请输入字段名',
                          }, {
                            validator: this.checkField,
                          }],
                          initialValue: obj.name
                        })(
                          <Input placeholder="请输入字段名"/>
                        )}
                      </Form.Item>
                      <Form.Item
                        label={<FormattedMessage id="app.customApi.Field-type"/>}
                        hasFeedback

                      >
                        {getFieldDecorator('fieldTypes', {
                          rules: [{
                            required: true, message: '请选择字段类型',
                          }, {
                            validator: '',
                          }],
                          initialValue: obj.fieldType
                        })(
                          <Select>
                            <Option value="string">字符串(string)</Option>
                            <Option value="boolean">布尔值(boolean)</Option>
                            <Option value="short">短整型(short)</Option>
                            <Option value="int">整型(int)</Option>
                            <Option value="long">长整型(long)</Option>
                            <Option value="double">双精度型(double)</Option>
                            <Option value="float">浮点型(float)</Option>
                          </Select>
                        )}
                      </Form.Item>

                    </div>
                  )
                 })

                : ''
             }
           </Form>
           <Button htmlType='button' onClick={()=>{this.addChildren()}} style={{display:this.state.display}}>
             <FormattedMessage id="app.customApi.Continue-to-increase" />
           </Button>
         </Modal>
       </div>
      )
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser
}))(Form.create()(EditModal));
